package com.kk.score.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kk.score.entity.DepartmentEntity;
import com.kk.score.entity.PositionEntity;
import com.kk.score.entity.vo.UserVo;
import com.kk.score.exception.RRException;
import com.kk.score.service.DepartmentService;
import com.kk.score.service.PositionService;
import com.kk.score.utils.PageUtils;
import com.kk.score.utils.Query;
import com.kk.score.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.kk.score.dao.UserDao;
import com.kk.score.entity.UserEntity;
import com.kk.score.service.UserService;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;


@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    HttpServletRequest httpServletRequest;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    UserService userService;

    @Autowired
    UserDao userDao;

    @Autowired
    DepartmentService departmentService;

    @Autowired
    PositionService positionService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String departmentUid = (String) params.get("departmentUid");
        String positionUid = (String) params.get("positionUid");
        String status = (String) params.get("status");
        if (!StringUtils.hasText(departmentUid)) {
            departmentUid = null;
        }
        if (!StringUtils.hasText(positionUid)) {
            positionUid = null;
        }
        if (!StringUtils.hasText(status)) {
            status = "1";
        }
        return new PageUtils(userDao.findUserPage(new Query<UserEntity>().getPage(params), departmentUid, positionUid, status));
    }

    @Override
    public Boolean login(UserVo user) {
        //如果是首次登录，则首先在数据库创建出这个用户，判断条件为，部门或职位是否有值
        String department = user.getDepartment();
        String position = user.getPosition();
        if (StringUtils.hasText(department) || StringUtils.hasText(position)) {
            UserEntity userEntity = new UserEntity();
            PositionEntity positionEntity = positionService.getOne(new LambdaQueryWrapper<PositionEntity>().eq(PositionEntity::getName, position));
            DepartmentEntity departmentEntity = departmentService.getOne(new LambdaQueryWrapper<DepartmentEntity>().eq(DepartmentEntity::getName, department));
            //判断数据库中是否有相关部门和职位,没有则添加
            if (Objects.isNull(positionEntity)) {
                positionEntity = new PositionEntity(position);
                positionEntity.insert();
            }
            if (Objects.isNull(departmentEntity)) {
                departmentEntity = new DepartmentEntity(department);
                departmentEntity.insert();
            }
            BeanUtils.copyProperties(user, userEntity);
            userEntity.setDepartmentUid(departmentEntity.getUid());
            userEntity.setPositionUid(positionEntity.getUid());
            userEntity.setPassword(passwordEncoder.encode(userEntity.getPassword()));
            userEntity.insert();
        }
        //manager 用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RRException("登录错误!");
        }
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        return true;
    }

    @Override
    public boolean deleteByDepartmentUids(String[] uids,Integer status) {
        return userDao.deleteByDepartmentUids(uids,status);
    }

    @Override
    public R changePassword(UserEntity user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userDao.updateById(user) == 1 ? R.ok().put("data",1) : R.error("修改失败！");
    }

}